<?php
/**
 * Created by Zhy
 * User: Zhy
 * Date: 2019/12/2
 * Time: 14:25
 */

namespace app\api\controller;


use think\Db;

class Apilogin extends Base
{

    /**
     * 账号密码登录
     * @return \think\response\Json
     * phone    手机号
     * pwd      密码
     */
    public function passwordLogin(){
        $phone = trim(input('phone'), ' ');
        $pwd = trim(input('pwd'), ' ');
        if($phone == '') return json(['status' => 0, 'msg' => '请填写手机号']);
        if($pwd == '') return json(['status' => 0, 'msg' => '请填写密码']);

        $user = Db::table('up_u_user')->where('user_phone', $phone)->find();
        if(empty($user)) return json(['status' => 0, 'msg' => '该手机号尚未注册']);

        $password = md5($pwd);
        if(!empty($user) && $password != $user['user_password']) return json(['status' => 0, 'msg' => '密码错误']);
        if($user['user_status'] == 2 || $user['user_status'] == 3) return json(['status' => 0, 'msg' => '账号异常，请联系管理员']);
        $token = $token = md5(date('YmdHis') . rand(100000, 999999));
        $data['user_last_time'] = date('Y-m-d H:i:s');
        $data['user_token'] = $token;
        $res = Db::table('up_u_user')->where('user_phone', $phone)->update($data);
        if($res){
            $userInfo = Db::table('up_u_user')->where('user_phone', $phone)->find();
            // todo:融云
            return json(['status' => 200, 'msg' => $userInfo]);
        }else{
            return json(['status' => 0, 'msg' => '登录失败']);
        }
    }

    /**
     * 发送验证码
     * @return \think\response\Json|void
     * phone       填写的手机号
     * type        发送场景   1 账号密码注册   2 重置密码||快捷登录   3 第三方登录时绑定手机号 4 绑定新手机号   其他传空
     * types       当type为3时，传此值  1 微信  2苹果
     * yzm         图形验证码
     */
    public function getPhoneCode()
    {
        $params = input('');
        
        if(trim($params['phone'], ' ') == '') {
            return json(['status' => 0, 'msg' => '请输入手机号']);
        }
        
        $userInfo = Db::table('up_u_user')->where('user_phone', $params['phone'])->find();
        if(!empty($userInfo) && isset($params['type']) && $params['type'] == 1) { //注册
            return json(['status' => 0, 'msg' => '该手机号已注册']);
        }
        if(empty($userInfo) && isset($params['type']) && $params['type'] == 2) { //找回密码
            return json(['status' => 0, 'msg' => '该账号不存在']);
        }
        if(!empty($userInfo) && $params['type'] == 3) {//第三方登录时绑定手机号
            if($params['types'] == 1) {
                $field = '_wx_';
            } elseif($params['types'] == 2) {
                $field = '_apple_';
            }

            if($userInfo["user{$field}token"]) {
                return json(['status' => 0, 'msg' => '此号码已被绑定']);
            }
        }
        
        if(!empty($userInfo) && $params['type'] == 4){
            return json(['status' => 0, 'msg' => '该手机号已注册']);
        }

    
        // 判断不同场景下的发送次数
//        $startTime = strtotime(date('Y-m-d 00:00:00'));//当天的起始时间
//        $endTime = strtotime(date('Y-m-d 23:59:59'));//当天的结束时间
//        $where = [];
//        $where['phone'] = $params['phone'];
//        $where['yzm_type'] = $params['send_type'];
//        $where['time'] = ['between', [$startTime, $endTime]];
//        $num = Db::table('up_phonecode')->where($where)->count('id');
//        if($num >= 5) {
//            return json(['status' => 0, 'msg' => '今日获取次数已用完，明天再来吧～']);
//        }
        $code = GetRandCode();//6位数验证码
        $sendres = YzxSms($code, $params['phone'], '');//发送验证码
        if($sendres['code'] != 0) {//发送不成功
            return json(['status' => 0, 'msg' => $sendres['msg']]);
        } else {
            $data = [
                'phone' => $params['phone'],//发送的手机号
                'code' => $code,//验证码
                'time' => time(),//验证码发送的时间戳
                'date_time' => date('Y-m-d H:i:s'),//日期格式
//                'yzm_type' => $params['send_type']
            ];
            $res = Db::table('up_phonecode')->insert($data);
            if(!$res) {
                return json(['status' => 0, 'msg' => '数据库操作失败']);
            }
            return json(['status' => 200, 'msg' => $code]);
        }
    }

    /**
     * 手机号验证码登录/注册
     * @return \think\response\Json
     * phone    手机号
     * code     验证码
     */
    public function phoneLogin(){
        $phone = trim(input('phone'), ' ');
        $code = trim(input('code'), ' ');
        if($phone == '') return json(['status' => 0, 'msg' => '请填写手机号']);
        if($code == '') return json(['status' => 0, 'msg' => '请填写验证码']);

        $user = Db::table('up_u_user')->where('user_phone', $phone)->find();
        if(!empty($user)){
            if($user['user_status'] == 2 || $user['user_status'] == 3){
                return json(['status' => 0, 'msg' => '账号异常，请联系管理员']);
            }
        }

        //=========验证验证码
        $yzm = Db::table('up_phonecode')
            ->where('phone', $phone)
            ->order('time desc')
            ->limit(1)
            ->find();
        if($code != $yzm['code']) return json(['status' => 0, 'msg' => '验证码错误']);
        // 10分钟超时
        $now = time();
        if($now - $yzm['time'] >= 1801) return json(['status' => 0, 'msg' => '验证码超时']);
        if($yzm['status'] == 1) return json(['status' => 0, 'msg' => '验证码失效']);

        $token = $token = md5(date('YmdHis') . rand(100000, 999999));
        $data['user_last_time'] = date('Y-m-d H:i:s');
        $data['user_token'] = $token;
        if($user){ // 登录
            $result = Db::table('up_u_user')->where('user_phone', $phone)->update($data);
            if($result){
                $userInfo = Db::table('up_u_user')->where('user_phone', $phone)->find();
                //修改验证码状态
                Db::table('up_phonecode')->where('id', $yzm['id'])->setField('status', 1);
                return json(['status' => 200, 'msg' => $userInfo]);
            }else{
                return json(['status' => 0, 'msg' => '快捷登录失败']);
            }
        }else{
            $data['user_phone'] = $phone;
            $data['user_time'] = date('Y-m-d H:i:s');
            $userid = Db::table('up_u_user')->insertGetId($data);
            if($userid){
                // 默认用户名    用户+ID
                Db::table('up_u_user')->where('user_id', $userid)->setField('user_username', '用户' . $userid);
                $userInfo = Db::table('up_u_user')->where('user_id', $userid)->find();
                //修改验证码状态
                Db::table('up_phonecode')->where('id', $yzm['id'])->setField('status', 1);
                // todo:融云
                return json(['status' => 200, 'msg' => $userInfo]);
            }else{
                return json(['status' => 0, 'msg' => '快捷登录失败']);
            }
        }
    }


    /**
     * 重置密码
     * @return \think\response\Json
     * phone     手机号
     * pwd       密码
     * code      验证码
     */
    public function resetPassword(){
        $phone = trim(input('phone'), ' ');
        $pwd = trim(input('pwd'), ' ');
        $code = trim(input('code'), ' ');
        if($phone == '') return json(['status' => 0, 'msg' => '请填写手机号']);
        if($code == '') return json(['status' => 0, 'msg' => '请填写验证码']);
        if($pwd == '') return json(['status' => 0, 'msg' => '请填写密码']);

        // 账号
        $exist = Db::table('up_u_user')->where('user_phone', $phone)->find();
        if(empty($exist)) return json(['status' => 0, 'msg' => '该账号未注册']);
        // 验证码
        $yzm = Db::table('up_phonecode')
            ->where('phone', $phone)
            ->order('time desc')
            ->limit(1)
            ->find();
        if($code != $yzm['code']) return json(['status' => 0, 'msg' => '验证码错误']);
        // 10分钟超时
        $now = time();
        if($now - $yzm['time'] >= 1801) return json(['status' => 0, 'msg' => '验证码失效']);
        if($yzm['status'] == 1) return json(['status' => 0, 'msg' => '验证码已使用']);
        $update = [
            'user_update_time' => date('Y-m-d H:i:s'),
            'user_password' => md5($pwd)
        ];
        $res = Db::table('up_u_user')->where('user_phone', $phone)->update($update);
        if($res){
            //修改验证码状态
            Db::table('up_phonecode')->where('id', $yzm['id'])->setField('status', 1);
            return json(['status' => 200, 'msg' => '重置成功']);
        }else{
            return json(['status' => 0, 'msg' => '重置失败']);
        }
    }
    /**
     * 账号密码注册
     * @return \think\response\Json
     * phone     手机号
     * pwd       密码
     * code      验证码
     */
    public function register(){
        $phone = trim(input('phone'), ' ');
        $pwd = trim(input('pwd'), ' ');
        $code = trim(input('code'), ' ');
        if($phone == '') return json(['status' => 0, 'msg' => '请填写手机号']);
        if($code == '') return json(['status' => 0, 'msg' => '请填写验证码']);
        if($pwd == '') return json(['status' => 0, 'msg' => '请填写密码']);
        
        // 账号
        $exist = Db::table('up_u_user')->where('user_phone', $phone)->find();
        if(!empty($exist)) return json(['status' => 0, 'msg' => '该账号已注册']);
        // 验证码
        $yzm = Db::table('up_phonecode')
            ->where('phone', $phone)
            ->order('time desc')
            ->limit(1)
            ->find();
        if($code != $yzm['code']) return json(['status' => 0, 'msg' => '验证码错误']);
        // 10分钟超时
        $now = time();
        if($now - $yzm['time'] >= 1801) return json(['status' => 0, 'msg' => '验证码失效']);
        if($yzm['status'] == 1) return json(['status' => 0, 'msg' => '验证码已使用']);
        $token = $token = md5(date('YmdHis') . rand(100000, 999999));
        $insert = [
            'user_phone' => $phone,
            'user_time' => date('Y-m-d H:i:s'),
            'user_password' => md5($pwd),
            'user_token'=>$token,
            'user_last_time'=>date('Y-m-d H:i:s')
        ];
        $res = Db::table('up_u_user')->insertGetId($insert);
        if($res){
            // 默认用户名    用户+ID
            Db::table('up_u_user')->where('user_id', $res)->setField('user_username', '用户' . $res);
            //修改验证码状态
            Db::table('up_phonecode')->where('id', $yzm['id'])->setField('status', 1);
            //查询这个用户
            $list = Db::table('up_u_user')->where('user_phone',$phone)->find();
            return json(['status' => 200, 'msg' => $list]);
        }else{
            return json(['status' => 0, 'msg' => '注册失败']);
        }
    }

    /**
     * 用户服务协议
     * @return \think\response\Json
     */
    public function user_agreement(){
        $agreement = Db::table('up_other')->where('other_id', 1)->value('other_user_agreement');
        if($agreement){
            return json(['status' => 200, 'msg' => $agreement]);
        }else{
            return json(['status' => 200, 'msg' => []]);
        }
    }

    /**
     * 用户隐私协议
     * @return \think\response\Json
     */
    public function user_ys(){
        $ys = Db::table('up_other')->where('other_id', 2)->value('other_ys_agreement');
        if($ys){
            return json(['status' => 200, 'msg' => $ys]);
        }else{
            return json(['status' => 200, 'msg' => []]);
        }
    }
    

    

    
    /**
     * 第三方登录第一步
     * @return \think\response\Json
     * login_type      1 apple   2 微信
     * third_token     微信传token,apple传ID
     */
    public function thirdLogin(){
        $login_type = input('login_type'); // 1 apple   2 微信   3 QQ
        $third_token = input('third_token'); // 微信、QQ传token，apple传ID
        if($login_type == 1){
            $field = 'user_apple_token';
        }elseif($login_type == 2){
            $field = 'user_wx_token';
        }
        $first_login = Db::table('up_u_user')->where($field, $third_token)->find();
        if($first_login){ // 有记录
            $token = $token = md5(date('YmdHis') . rand(100000, 999999));
            $update = [
                'user_last_time' => date('Y-m-d H:i:s'),
                'user_token' => $token
            ];
            $res = Db::table('up_u_user')->where('user_id', $first_login['user_id'])->update($update);
            if($res){
                $userInfo = Db::table('up_u_user')->where('user_id', $first_login['user_id'])->find();
                // todo:融云
                return json(['status' => 200, 'msg' => $userInfo]);
            }else{
                return json(['status' => 0, 'msg' => '登录失败']);
            }
        }else{
            // 第一次登录，先绑定手机
            return json(['status' => 201, 'msg' => '']);
        }
    }
    
    /**
     * 第三方登录第二步
     * @return \think\response\Json
     * phone           手机号
     * code            验证码
     * login_type      登录方式  1 apple  2 微信
     * third_token     第三方token
     * third_nickname  第三方昵称，apple传空
     * third_image     第三方头像，apple传空
     */
    public function thirdLoginS(){
        $phone = input('phone');
        $code = input('code');
        $login_type = input('login_type');
        $third_token = input('third_token');
        $third_nickname = input('third_nickname');
        $third_image = input('third_image');
        if($login_type == 1){
            $field = 'user_apple_token';
        }elseif($login_type == 2){
            $field = 'user_wx_token';
        }
        
        if($phone == '') return json(['status' => 0, 'msg' => '请填写手机号']);
        if($code == '') return json(['status' => 0, 'msg' => '请填写验证码']);
        //=========验证验证码
        $yzm = Db::table('up_phonecode')
            ->where('phone', $phone)
            ->order('time desc')
            ->limit(1)
            ->find();
        if($code != $yzm['code']) return json(['status' => 0, 'msg' => '验证码错误']);
        // 10分钟超时
        $now = time();
        if($now - $yzm['time'] >= 1801) return json(['status' => 0, 'msg' => '验证码超时']);
        if($yzm['status'] == 1) return json(['status' => 0, 'msg' => '验证码失效']);
        
        $have = Db::table('up_u_user')->where('user_phone', $phone)->find();
        $token = $token = md5(date('YmdHis') . rand(100000, 999999));
        if($have){ // 绑定已存在的手机号
            $update = [
                'user_token' => $token,
                'user_last_time' => date('Y-m-d H:i:s'),
                $field => $third_token
            ];
            if($login_type == 2){
                $update['user_wx_img'] = $third_image;
                $update['user_wx_nickname'] = $third_nickname;
            }
            $res = Db::table('up_u_user')->where('user_phone', $phone)->update($update);
        }else{
            $insert = [
                'user_phone' => $phone,
                'user_token' => $token,
                $field => $third_token,
                'user_time' => date('Y-m-d H:i:s'),
                'user_last_time' => date('Y-m-d H:i:s')
            ];
            if($login_type == 2){
                $insert['user_wx_img'] = $third_image;
                $insert['user_wx_nickname'] = $third_nickname;
                $insert['user_image'] = $third_image;
                $insert['user_username'] = $third_nickname;
            }
            $res = Db::table('up_u_user')->insertGetId($insert);
            // 默认用户名    用户+ID
            Db::table('up_u_user')->where('user_id', $res)->setField('user_username', '用户' . $res);
        }
        if($res){
            //修改验证码状态
            Db::table('up_phonecode')->where('id', $yzm['id'])->setField('status', 1);
            $userInfo = Db::table('up_u_user')->where('user_phone', $phone)->find();
            // todo:融云
            return json(['status' => 200, 'msg' => $userInfo]);
        }else{
            return json(['status' => 0, 'msg' => '登录异常']);
        }
    }

    //第三方设置密码
    public function setPwd(){
        $pwd = trim(input('pwd'), ' ');
        $user_id = trim(input('user_id'),' ');
        $insert = [
            'user_time' => date('Y-m-d H:i:s'),
            'user_password' => md5($pwd)
        ];
        $res = Db::table('up_u_user')->where('user_id', $user_id)->update($insert);
        if($res){
            //修改验证码状态
            return json(['status' => 200, 'msg' =>$res]);
        }else{
            return json(['status' => 0, 'msg' => '重置失败']);
        }
    }
    



    

}